package com.hnbtr.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class JsonInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String origin  = request.getHeader("origin");
		if (StringUtils.hasText(origin)) {
			response.setHeader("Access-Control-Allow-Origin", origin);
		}
		
		response.setHeader("Access-Control-Allow-Credentials", "true");
		response.setHeader("Access-Control-Allow-Methods", "*");
		
		String headers = request.getHeader("Access-Control-Request-Headers");
		if (StringUtils.hasText(headers)) {
			response.setHeader("Access-Control-Allow-Headers", headers);
		}
		
		response.setHeader("Access-Control-Max-Age", "3600");
		return true;
	}
	
}
